package com.cy.milktea.controller;

import com.cy.milktea.pojo.System.JsonResult;
import com.cy.milktea.pojo.Stock;
import com.cy.milktea.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/stock")
public class StockController {

    @Autowired
    private StockService stockService;

    @PostMapping
    public JsonResult add(@RequestBody Stock stock) {

        stockService.add(stock);
        return JsonResult.ok("添加成功!");
    }

    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable Integer id) {
        stockService.delete(id);
        return JsonResult.ok("删除成功!");
    }

    @PutMapping
    public JsonResult update(@RequestBody Stock stock) {
        stockService.update(stock);
        return JsonResult.ok("修改成功!");
    }

    @GetMapping
    public JsonResult query(String name, String stockDateStr, String sort){
        if(name != null) name = "".equals(name.trim()) ? null : name.trim();
        Date stockDate = null;
        if(stockDateStr != null && !"".equals(stockDateStr.trim())) {
            try {
                stockDate = new SimpleDateFormat("yyyy-MM-dd").parse(stockDateStr);
            }catch (ParseException e) {

            }
        }
        sort = "0".equals(sort) ? "ASC" : "DESC";
        return JsonResult.ok("查询成功!",stockService.query(name,stockDate,sort));
    }
}
